package com.jarveis.frame.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * FTP传输
 * 
 * @author liuguojun
 */
public class FtpTransfer implements NetTransfer {

	private static final Logger logger = Logger.getLogger(FtpTransfer.class);

	private String host; // 主机
	private int port = 0; // 端口
	private String user; // 用户
	private String password; // 密码
	private FTPClient client = new FTPClient();

	public FtpTransfer(String host, int port, String user, String password) {
		this.host = host;
		this.port = port;
		this.user = user;
		this.password = password;
	}

	public boolean connect() throws Exception {
		client.connect(host, port);
		if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
			if (client.login(user, password)) {
				// 设置控制台编码
				client.setControlEncoding("GBK");
				// 设置被动模式
				client.enterLocalPassiveMode();
				// 设置以二进制方式传输
				client.setFileType(FTP.BINARY_FILE_TYPE);
				logger.info("logined ftp server. --->" + host);
				
				return true;
			}
		}
		disconnect();
		logger.info("net error. --->" + host);
		
		return false;
	}

	public boolean disconnect() throws Exception {
		if (client.isConnected()) {
			client.disconnect();
		}

		return true;
	}

	public boolean download(String remote, String local) throws Exception {
		// 检查远程文件是否存在
		final FTPFile[] files = client.listFiles(remote);
		if (files.length != 1) {
			logger.info("远程文件不存在");
			return false;
		}

		client.retrieveFile(remote, new FileOutputStream(local));

		return true;
	}
	
	public byte[] download(String remote) throws Exception {
		return null;
	}

	public boolean upload(String local, String remote) throws Exception {
		File localFile = new File(local);
		if (localFile.isDirectory()) {
			return true;
		}

		// 对远程目录的处理
		String remoteFileName = remote;
		if (remote.contains("/")) {
			remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
			// 创建服务器远程目录结构，创建失败直接返回
			if (!CreateDirecroty(remote)) {
				return false;
			}
		}

		client.storeFile(remoteFileName, new FileInputStream(local));
		logger.info("upload file success. --->" + remote);

		return true;
	}
	
	public boolean upload(byte[] byteArr, String remote) throws Exception {
		return false;
	}

	public boolean CreateDirecroty(String remote) throws Exception {
		String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
		if (!directory.equalsIgnoreCase("/")
				&& !client.changeWorkingDirectory(directory)) {
			// 如果远程目录不存在，则递归创建远程服务器目录
			int start = 0;
			int end = 0;
			if (directory.startsWith("/")) {
				start = 1;
				// 切换到根目录
				client.changeWorkingDirectory("/");
			} else {
				start = 0;
			}
			end = directory.indexOf("/", start);
			while (true) {
				String subDirectory = remote.substring(start, end);
				if (!client.changeWorkingDirectory(subDirectory)) {
					if (client.makeDirectory(subDirectory)) {
						client.changeWorkingDirectory(subDirectory);
						logger.info("create folder success. --->" + subDirectory);
					} else {
						logger.info("create folder failed. --->" + subDirectory);
						return false;
					}
				}
				start = end + 1;
				end = directory.indexOf("/", start);

				// 检查所有目录是否创建完毕
				if (end <= start) {
					break;
				}
			}
		}
		return true;
	}

	public boolean remove(String remote) throws Exception {
		return false;
	}

}
